package com.uwo.house.config;

import com.alibaba.fastjson.JSONObject;
import com.uwo.house.advice.Code;
import com.uwo.house.kits.CacheKits;
import com.uwo.house.kits.JwtKits;
import org.apache.log4j.Logger;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.AccessControlFilter;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import java.io.OutputStream;

/**
 * token 验证
 * Created by yanhao on 2017/7/16.
 */
public class JWTAuthenticationFilter extends AccessControlFilter {

    private final Logger log = Logger.getLogger(JWTAuthenticationFilter.class);

    protected static final String AUTHORIZATION_HEADER = "Authorization";

    @Override
    protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) {
        return false;
    }

    @Override
    protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {
        String requestURL = getPathWithinApplication(request);//获取url
        HttpServletRequest httpRequest = (HttpServletRequest)request;
        String access_token = httpRequest.getHeader("Authorization");
        if(access_token != null) {
            String[] strs = access_token.split(" ");
            access_token = (strs.length == 2) ? strs[1] : null;
        }
        JWTAuthenticationToken jwtToken = null;
        // 4、如当前URL匹配拦截器名字（URL模式）
        if (requestURL.endsWith("login") && access_token == null) {
            // 2、客户端传入的用户身份 不用每次请求都带上用户信息
            String userName = request.getParameter("username");
            String passWord = request.getParameter("password");
            String provider = request.getParameter("provider");
            jwtToken = new JWTAuthenticationToken(userName, passWord, provider);
        } else {
            if(access_token == null)
                return error(response, Code.UNAUTHORIZED);
//                throw new AccessTokenException(Code.UNAUTHORIZED, "未授权");
            // 验证access_token
            if (!JwtKits.verifyToken(access_token, "123456"))
                return error(response, Code.ACCESS_TOKEN_INVALID);
//                throw new AccessTokenException(Code.ACCESS_TOKEN_INVALID, "access_token无效");
            //页面传入jwt的token
            jwtToken = (JWTAuthenticationToken)CacheKits.get(access_token);
        }
        try {
            // 5、委托给Realm进行登录
            Subject subject = getSubject(request, response);
            subject.login(jwtToken);
            return true;
        }catch (Exception e){
            return error(response, Code.UNAUTHORIZED);
//            throw new AccessTokenException(Code.UNAUTHORIZED, "未授权");
        }
    }

    private boolean error(ServletResponse response, Code code){
        try {
            JSONObject json = new JSONObject();
            json.put("code", code.getCode());
            json.put("message", code.getMessage());
            OutputStream out = response.getOutputStream();
            out.write(json.toString().getBytes());
            out.flush();
        }catch(Exception e){
            e.printStackTrace();
        }
        return false;
    }

}
